/*
 * Copyright 2014 Matyas Mazzag
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mcubed.soapui


import org.codehaus.groovy.control.ConfigurationException

import com.eviware.soapui.model.testsuite.TestCaseRunner



/**
 * This class can be used to resolve classes/scripts.
 * <br />
 * The implementation first tries to load the configured root.dir from the TestSuite's property.
 * If that fails it will tried to load the root.dir from an environment variable.
 *
 * @author Matyas Mazzag
 *
 */
abstract class FilePathResolver {
	private final TestCaseRunner testRunner
	private final String propertyName
	private final String envVariableName
	def resolvedVia


	/**
	 * Constructor that initialises members
	 * 
	 * @param testRunner
	 * @param propertyName
	 * @param envVariableName
	 */
	FilePathResolver( TestCaseRunner testRunner, String propertyName, String envVariableName ) {
		this.testRunner = testRunner
		this.propertyName = propertyName
		this.envVariableName = envVariableName
	}
	
	/**
	 * Resolves the root directory by first searching for a custom property set on the TestSuite.
	 * The fallback is to lookup an environment variable.
	 * 
	 * @return
	 */
	def File resolve() {
		def rootDir = testRunner.testCase.testSuite.properties[ propertyName ]?.value
		
		if( !rootDir ) {
			rootDir = System.getenv( envVariableName )
		} else {
			resolvedVia = "Resolved from Custom Property '$propertyName' from TestSuite named '$testRunner.testCase.testSuite.name'"
		}
		
		if( !rootDir ) {
			throw new ConfigurationException( "Missing environment property '$envVariableName' or missing TestSuite property '$propertyName'. At least one of them should be defined otherwise can't resolve external files." )
		} else if( !resolvedVia ) {
			resolvedVia = "Resolved from Environment variable '$envVariableName'"
		}
		
		return new File( rootDir )
	}
	
	/**
	 * Resolves a file by prepending it with the root.dir if the file is not absolute. 
	 * 
	 * @param pathToFile
	 * @return
	 */
	def File resolve( String pathToFile ) {
		File candidate = new File( pathToFile )
		
		if( !candidate.absolute ) {
			candidate = new File( resolve(), pathToFile )
		}
		
		return candidate
	}
	
}
